package com.szalay.desktopsearch.ui;

import com.szalay.desktopsearch.indexer.Fields;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Map;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;

/**
 * Displays a single item of a search result.
 * @author szalay
 */
public class SearchResultItem extends JPanel {
    private static final long serialVersionUID = 1761437868624134176L;

    private final JButton button;
    
    public SearchResultItem(final SolrDocument document, final QueryResponse response, final int parentWidth) {
        super(new BorderLayout(), true);
        
        //add a label with the path
        final String path = (String) document.getFieldValue(Fields.PATH);
        button = new JButton(path);
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                final JPopupMenu popup = new JPopupMenu();
                for (final Action action : DetailsToolBar.getDocumentActions(document, popup)) {
                    popup.add(action);
                }
                popup.add(new ShowDetailsAction(document, response, popup));
                popup.setLocation(e.getXOnScreen(), e.getYOnScreen());
                popup.pack();
                popup.setVisible(true);
            }
        });
        button.setBorderPainted(false);
        add(button, BorderLayout.NORTH);
        
        //Display the score
        add(new JLabel(document.getFieldValue("score").toString()), BorderLayout.SOUTH);
        
        //Display the highlighting
        final Map<String, List<String>> get = 
                response.getHighlighting().get(document.getFieldValue(Fields.PATH).toString());
        if (!get.isEmpty()) {
            final String firstKey = get.keySet().iterator().next();
            final List<String> listForFirstKey = get.get(firstKey);
            add(new JLabel("<html>" + listForFirstKey.get(0) + "</html>"), BorderLayout.CENTER);
        }
        
        setSize(300, 30);
    }

    @Override
    public void setBackground(Color bg) {
        super.setBackground(bg);
        if (button != null) {
            button.setBackground(bg);
        }
    }
}
